package com.wl.application.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author wl
 * @version 1.0
 * @date 2022/7/26
 * @description:
 */
@Configuration
public class MyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.拦截请求
        System.out.println("成功拦截请求！");
        //2.获得请求的参数
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        System.out.println("request.getLocalAddress() = " + request.getLocalAddress());
        System.out.println("request.getHeaders() = " + request.getHeaders());
        System.out.println("request.getMethodValue() = " + request.getMethodValue());
        System.out.println("request.getMethod().name() = " + request.getMethod().name());
        System.out.println("request.getQueryParams().toSingleValueMap() = " + request.getQueryParams().toSingleValueMap());
        //3.业务处理
        System.out.println("业务处理");
        Mono<Void> filter=null;
        if (Integer.valueOf(request.getQueryParams().toSingleValueMap().get("age"))==18) {
            //4.放行
            filter = chain.filter(exchange);
        }else{
            filter=errorInfo(exchange,"出现错误！");
        }

        return filter;
    }

    // 响应错误信息
    public static Mono<Void> errorInfo(ServerWebExchange exchange, Object r) {
        return Mono.defer(() -> {
            // 把对象转成JSON
            byte[] bytes = bytes = JSON.toJSONBytes(r);
            // 获取响应对象
            ServerHttpResponse response = exchange.getResponse();
            // 响应响应类型
            response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
            // 设置HTTP响应码
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Flux.just(buffer));
        });
    }
    /**
     * 可设置当前过滤器的优先级
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
